(function ($, window, document) {

    var classSelector = function (name) {
        return '.' + $.className(name);
    }

    var MemberSelect = $.MemberSelect = $.Class.extend({
        init: function (data, selectItems, options) {
            var self = this;
            self.data = data || [];
            self.options = options || {};
            if (!self.options.onlyDept)
                self.options.onlyDept = false;
            self.currentRootId = "";
            self.parenRootId = "";
            self.isShowSelected = false;
            self.selectItems = selectItems || [];
            self.dataInfo = {};
            self.checkboxList = [];
            self.parseData(data);
        },

        parseData: function (items, parentId) {
            if (typeof (parentId) == "undefined") {
                parentId = "";
            }
            var self = this;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var text = item["text"];
                var value = item["value"];
                var children = item["children"];
                var isDept = false;
                var countInfo = {
                    memberCount: 0,
                    deptCount: 0
                };
                if (value.substr(0, 2) == "d_") {
                    isDept = true;
                    if (children.length > 0) {
                        countInfo = self.getChildrenMemeberCount(children, 0);
                        self.parseData(children, value);
                    }
                }
                self.dataInfo[value] = {
                    value: value,
                    text: text,
                    isDept: isDept,
                    parent: parentId,
                    childrenCount: countInfo.memberCount,
                    childrenDeptCount: countInfo.deptCount
                };
            }
        },

        onlyDept: function (b) {
            var self = this;
            self.options.onlyDept = b;
        },

        getMainHeight: function () {
            var self = this;
            var positionInfo = self.el.main.getBoundingClientRect();
            var height = positionInfo.height;
            return height;
        },

        createMain: function () {
            var div = document.createElement('div');
            div.style = "width:100%;height:100%;border:none;position:fixed;top:0;left:0;z-index:999;background-color:#fff;";
            document.body.appendChild(div);
            return div;
        },

        createDom: function () {
            var self = this;
            self.el = self.el || {};
            self.el.main = self.createMain();
            self.el.header = self.createHeader();
            self.el.content = self.createContent();
            self.el.footer = self.createFooter();

            self.setDataSource();
        },

        createContent: function () {
            var self = this;
            var div = document.createElement('div');
            div.className = "mui-content";
            var height = self.getMainHeight();
            div.style = "overflow:auto;height:" + (height - 50) + "px;";
            //self.createSearchInput(div);
            self.createSelectAll(div);
            var ul = document.createElement('ul');
            ul.className = "mui-table-view";
            ul.style = "margin-top:0;";
            self.el.dataUl = ul;
            div.appendChild(ul);
            self.el.main.appendChild(div);
            return div;
        },

        setDataSource: function (data) {
            var self = this;
            self.el.dataUl.innerHTML = "";
            var items = [];
            if (typeof (data) != "undefined") {
                items = data;
            } else {
                items = self.getCurrentData();
            }
            self.checkboxList = [];
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var text = item["text"];
                var value = item["value"];
                var info = self.getDataInfo(value);
                var li = document.createElement('li');
                li.className = "mui-table-view-cell mui-left";
                var label = document.createElement('label');
                label.className = "mui-checkbox";
                label.style = "padding: 11px 15px;overflow: hidden;";
                var radio = document.createElement('input');
                radio.name = "radio_" + value;
                radio.type = "checkbox";
                radio.style = "left:0px;top: 6px;";
                radio.value = value;
                radio.setAttribute("data-value", value);
                radio.setAttribute("data-text", text);
                if (self.selectItems.indexOf(value) >= 0) {
                    radio.checked = true;
                }
                radio.addEventListener('change', function (sender, p) {
                    self.selectValue(this);
                });
                if (info != null && info.isDept) {
                    if (!self.options.onlyDept) {
                        text += " <span style='color:#666'>(" + info.childrenCount + "人)</span>";
                    }
                    if (info.childrenDeptCount > 0) {
                        text += " <span style='color:#666'>(" + info.childrenDeptCount + "个子部门)</span>";
                    }
                }
                if (!self.isShowSelected) {
                    self.checkboxList.push(radio);
                    label.appendChild(radio);
                }

                var span = document.createElement('span');
                span.style = "padding-left:20px;";
                if (self.isShowSelected)
                    span.style = "padding-left:0px;";
                span.innerHTML = text;
                label.append(span);
                li.appendChild(label);
                var info = self.getDataInfo(value);
                if (!self.isShowSelected && info != null && info.isDept) {
                    if (self.options.onlyDept && info.childrenDeptCount == 0) {

                    } else {
                        var button = document.createElement('button');
                        button.type = "button";
                        button.className = "mui-btn mui-btn-link";
                        if (info.childrenCount == 0 && info.childrenDeptCount == 0) {
                            button.className = "mui-btn mui-btn-link mui-disabled";
                        } else {
                            button.addEventListener('click', function (e) {
                                self.toggleChild(this);
                            });
                        }
                        button.innerText = "下级";
                        button.setAttribute("data-id", value);
                        li.append(button);
                    }
                }
                if (self.isShowSelected) {
                    var button = document.createElement('button');
                    button.type = "button";
                    button.className = "mui-btn mui-btn-link";
                    button.addEventListener('click', function (e) {
                        self.removeSeleced(this);
                    });
                    button.innerText = "移除";
                    button.setAttribute("data-id", value);
                    li.append(button);
                }
                self.el.dataUl.appendChild(li);
            }
        },

        createSearchInput: function (div) {
            var self = this;
            var sdiv = document.createElement('div');
            sdiv.className = "mui-input-row mui-search";
            var input = document.createElement('input');
            input.type = "text";
            input.style = "margin:0";
            input.placeholder = "搜索";
            input.className = "mui-input-clear";
            input.addEventListener('change', function (sender, p) {
                self.filterData(this);
            });
            sdiv.appendChild(input);
            div.appendChild(sdiv);
            self.el.searchInput = sdiv;
        },

        createSelectAll: function (div) {
            var self = this;

            var ul = document.createElement('ul');
            ul.className = "mui-table-view";
            ul.style = "margin-top:0;margin-bottom: 0;border-bottom: solid 1px #999;";
            var li = document.createElement('li');
            li.className = "mui-table-view-cell mui-left";
            var label = document.createElement('label');
            label.className = "mui-checkbox";
            label.style = "padding: 11px 15px;overflow: hidden;";
            var radio = document.createElement('input');
            radio.name = "radio_selectAll";
            radio.type = "checkbox";
            radio.style = "left:0px;top: 6px;";
            radio.addEventListener('change', function (sender, p) {
                self.selectAll(this);
            });
            label.appendChild(radio);
            var span = document.createElement('span');
            span.style = "padding-left:20px;";
            span.innerHTML = "全选";
            label.append(span);
            li.appendChild(label);
            ul.appendChild(li);
            div.appendChild(ul);
            self.el.selectAllCheckbox = radio;
            self.el.selectAll = ul;
        },

        createHeader: function () {
            var self = this;
            var header = document.createElement('header');
            header.className = "mui-bar mui-bar-nav";

            var header_back = document.createElement('a');
            header_back.className = "mui-icon mui-icon-left-nav mui-pull-left";
            header_back.addEventListener('click', function () {
                self.back();
            });
            var header_title = document.createElement('h1');
            header_title.className = "mui-title";
            header_title.innerText = "请选择";
            var header_select = document.createElement('a');
            header_select.className = "mui-btn mui-btn-link mui-pull-right mui-disabled"; //mui-disabled
            header_select.innerText = "上级";
            header_select.style = "color:#fff;";
            header_select.setAttribute("data-id", "");
            header_select.addEventListener('click', function () {
                self.toggleChild(this);
            });
            self.el.header_select = header_select;
            header.appendChild(header_back);
            header.appendChild(header_title);
            header.appendChild(header_select);
            self.el.main.appendChild(header);
            self.el.header_title = header_title;
            return header;
        },

        changeTitle: function (title) {
            var self = this;
            self.el.header_title.innerText = title;
        },

        createFooter: function () {
            var self = this;
            var footer = document.createElement('footer');
            footer.className = "bar-ope";
            var divLabel = document.createElement('div');
            divLabel.className = "mui-left";
            divLabel.style = "float:left;padding-top:15px;padding-left:5px;color:#007aff;";
            self.el.selectTip = divLabel;
            footer.appendChild(divLabel);
            var div = document.createElement('div');
            div.className = "footer-btn";
            var buttonBack = document.createElement('button');
            buttonBack.className = "btn-default";
            buttonBack.style = "display:none";
            buttonBack.type = "button";
            buttonBack.innerText = "返回";
            buttonBack.addEventListener('click', function () {
                self.back();
            });
            div.appendChild(buttonBack);
            var button = document.createElement('button');
            button.className = "btn-blue";
            button.type = "button";
            button.innerText = "确定";
            button.addEventListener('click', function () {
                self.confirm();
            });
            div.appendChild(button);
            footer.appendChild(div);
            self.el.buttonBack = buttonBack;
            self.el.footer = footer;
            self.el.main.appendChild(footer);
            return footer;
        },

        getCurrentData: function () {
            var self = this;
            var items = self.data;
            var rootId = self.currentRootId;
            if (rootId == "") return items;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var text = item["text"];
                var value = item["value"];
                var children = item["children"];
                if (value == rootId) {
                    return children;
                }
                var r = self.getChildrenData(rootId, children);
                if (r != null) {
                    return r;
                }
            }
            return [];
        },

        getChildrenData: function (deptId, children) {
            var self = this;
            for (var i = 0; i < children.length; i++) {
                var item = children[i];
                var value = item["value"];
                var children2 = item["children"];
                if (value == deptId) {
                    return children2;
                }
                if (children2.length > 0) {
                    var r = self.getChildrenData(deptId, children2);
                    if (r != null) {
                        return r;
                    }
                }
            }
            return null;
        },

        selectAll: function (obj) {
            var self = this;
            var checked = obj.checked;
            for (var i = 0; i < self.checkboxList.length; i++) {
                self.checkboxList[i].checked = checked;
                self.selectValue(self.checkboxList[i]);
            }
        },

        filterData: function (obj) {
            var self = this;
            var value = obj.value;

        },

        show: function (data, selectItems, onConfirm) {
            var self = this;
            self.data = data || [];
            self.selectItems = selectItems || [];
            self.onConfirm = onConfirm;
            self.parseData(data);
            self.createDom();
            self.selectTip();
        },

        close: function (obj) {
            var self = this;
            self.currentRootId = "";
            self.parenRootId = "";
            self.selectItems = [];
            self.hideSelected();
            self.el.main.parentNode.removeChild(self.el.main);
        },

        confirm: function () {
            var self = this;
            var selectItems = self.selectItems;
            var selectText = "";
            var selectValue = "";
            for (var i = 0; i < selectItems.length; i++) {
                var id = selectItems[i];
                var info = self.getDataInfo(id);
                if (info == null) continue;
                selectText += info.text + ",";
                selectValue += id + ",";
            }
            if (selectValue.length > 0) {
                selectValue = selectValue.substr(0, selectValue.length - 1);
            }
            if (selectText.length > 0) {
                selectText = selectText.substr(0, selectText.length - 1);
            }
            var result = {
                items: selectItems,
                value: selectValue,
                text: selectText
            };
            console.dir(result);
            if (typeof (self.onConfirm) == "function") {
                self.onConfirm(result);
            }
            self.close();
        },

        back: function () {
            var self = this;
            if (self.isShowSelected) {
                self.hideSelected();
            } else {
                self.close(this);
            }
        },

        removeSeleced: function (obj) {
            var self = this;
            var id = obj.getAttribute("data-id");
            var items = self.selectItems;
            for (var i = items.length - 1; i >= 0; i--) {
                var item = items[i];
                if (id == item) {
                    items.splice(i, 1);
                }
            }
            self.selectItems = items;
            self.showSelected();
        },

        toggleChild: function (obj) {
            var self = this;
            self.el.selectAllCheckbox.checked = false;
            var id = obj.getAttribute("data-id");
            if (id.length > 0) {
                var info = self.getDataInfo(id);
                self.parenRootId = info.parent;
            } else {
                self.parenRootId = "";
            }
            if (id == "") {
                self.el.header_select.className = "mui-btn mui-btn-link mui-pull-right mui-disabled"; //mui-disabled
            } else {
                self.el.header_select.className = "mui-btn mui-btn-link mui-pull-right"; //
            }
            self.el.header_select.setAttribute("data-id", self.parenRootId);
            self.currentRootId = id;
            self.setDataSource();

            return false;
        },

        showSelected: function () {
            var self = this;
            var result = [];
            var items = self.selectItems;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if (item.length > 0) {
                    var info = self.getDataInfo(item);
                    if (info != null) {
                        result.push({
                            text: info.text,
                            value: info.value
                        });
                    }
                }
            }
            self.isShowSelected = true;
            self.changeTitle("已选择");
            self.el.selectTip.innerHTML = "";
            self.el.header_select.innerText = "";
            self.el.buttonBack.style = "";
            //self.el.searchInput.style = "display:none;";
            self.el.selectAll.style = "display:none;";
            self.setDataSource(result);
        },

        hideSelected: function () {
            var self = this;
            self.isShowSelected = false;
            self.changeTitle("请选择");
            self.selectTip();
            self.el.buttonBack.style = "display:none;";
            self.el.header_select.innerText = "上级";
            //self.el.searchInput.style = "";
            self.el.selectAll.style = "margin-top:0;margin-bottom: 0;border-bottom: solid 1px #999;";
            self.setDataSource();

        },

        selectValue: function (obj) {
            var self = this;
            var id = obj.value;
            var checked = obj.checked;

            if (checked) {
                self.selectItems.push(id);
            } else {
                var items = self.selectItems;
                for (var i = items.length - 1; i >= 0; i--) {
                    var item = items[i];
                    if (id == item) {
                        items.splice(i, 1);
                    }
                }
                self.selectItems = items;
            }
            self.selectTip();
        },

        getDataInfo: function (id) {
            var self = this;
            if (typeof (self.dataInfo[id]) == "undefined")
                return null;
            return self.dataInfo[id];
        },

        getDeptChildrenCount: function (deptId) {
            var self = this;
            var dataInfo = self.getDataInfo(deptId);
            if (dataInfo == null) return 0;
            return dataInfo.childrenCount;
        },

        getChildrenMemeberCount: function (children, memberCount, deptCount) {
            var self = this;
            if (typeof (memberCount) == "undefined") {
                memberCount = 0;
            }
            if (typeof (deptCount) == "undefined") {
                deptCount = 0;
            }
            for (var i = 0; i < children.length; i++) {
                var item = children[i];
                var value = item["value"];
                var children2 = item["children"];
                if (value.substr(0, 2) == "u_") {
                    memberCount++;
                } else {
                    deptCount++;
                }
                if (children2.length > 0) {
                    var r = self.getChildrenMemeberCount(children2, memberCount, deptCount);
                    if (r != null) {
                        memberCount = r.memberCount;
                        deptCount = r.deptCount;
                    }
                }
            }
            return {
                memberCount: memberCount,
                deptCount: deptCount
            };
        },

        selectTip: function () {
            var self = this;
            if (self.isShowSelected) return;
            var items = self.selectItems;
            var memberCount = 0;
            var deptCount = 0;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if (item.length == 0) continue;
                if (item.substr(0, 2) == "d_") {
                    var info = self.getDataInfo(item);
                    deptCount += info.childrenDeptCount + 1;
                    memberCount += info.childrenCount;
                } else {
                    memberCount++;
                }
            }
            var text = "已选择:" + memberCount + "人";
            if (deptCount > 0) {
                text += "，其中有" + deptCount + "个部门";
            }
            self.el.selectTip.addEventListener('click', function (e) {
                self.showSelected();
            });
            self.el.selectTip.innerHTML = text;
        }
    });

    $.fn.memberSelect = function (options) {
        this.each(function (i, element) {
            if (element.memberSelect) return;
            element.memberSelect = new MemberSelect(element, options);
        });
        return this[0] ? this[0].memberSelect : null;
    };

})(mui, window, document);